<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* RESOURCEKEYWORDCATEGORY class
*
* Deal with resource's categories and keywords
*****/
class RESOURCEKEYWORDCATEGORY
{
// Constructor
	function RESOURCEKEYWORDCATEGORY($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/SUCCESS.php");
		$this->success = new SUCCESS();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/MISC.php");
		include_once("core/html/FORM.php");
		include_once("core/html/HTML.php");
		$this->html = new HTML($this->db);
		include_once("core/html/TABLE.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		include_once("core/html/CLOSE.php");
		include_once("core/keyword/KEYWORD.php");
		$this->keyword = new KEYWORD($this->db);
	}
// display the editing form:
	function editDisplay()
	{
		$this->checkInput();
		$this->template->setVar('heading', $this->messages->text("heading", "categoryKeyword"));
		$this->template->setVar('formStart', FORM::formHeader("resourceKeywordCategoryWrite"));
		include_once("core/group/GROUP.php");
		$group = new GROUP($this->db);
		$groups = $group->grabAll();
		if(sizeof($groups) > 1)
		{
// Put 1 => 'General' group at top of list
			unset($groups[1]);
			$temp[1] = 'General';
			foreach($groups as $key => $value)
				$temp[$key] = $value;
			$groups = $temp;
		}
		else
			$groups = FALSE;
		$keywords = $this->keyword->grabAll();
		$pString = '';
		if(is_array($groups))
		{
			$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
			$pString .= TABLE::trStart();
			$pString .= TABLE::td(MISC::b($this->messages->text("resources", "categories")) . MISC::br() . 
			$this->messages->text("hint", "categories"));
			$selectedArray = explode(",", $this->vars['groupIds']);
			$td = FORM::selectedBoxValueMultiple(FALSE, "groupIds", 
				$groups, $selectedArray, "6");
			$pString .= TABLE::td($td . MISC::br() . $this->messages->text("hint", "multiples"));
			$pString .= TABLE::trEnd();
			$pString .= TABLE::tableEnd();
			$pString .= MISC::br();
		}
		if(is_array($keywords))
		{
			$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
			$pString .= MISC::br();
			if(array_key_exists('keywordIds', $this->vars))
			{
				foreach(split(",", $this->vars['keywordIds']) as $value)
					$keywordIds[] = "'$value'";
				$condition = $this->db->formatField('id') . "=" . join(" OR " .
					$this->db->formatField('id') . "=", $keywordIds);
				$recordset = $this->db->select(array('WKX_keyword'), array("id", "keyword"), 
					" WHERE " . $condition . " ORDER BY " . $this->db->formatField('keyword'));
				while($line = $this->db->loopRecordSet($recordset))
					$this->keywordArray[] = $line['keyword'];
				$keywordString = join(', ', $this->keywordArray);
			}
			else
				$keywordString = FALSE;
			$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
			$pString .= TABLE::trStart();
// Entry text area
			$pString .= TABLE::td(FORM::textareaInput(MISC::b($this->messages->text("resources", "keywords")), 
				"keywords", $this->html->dbToFormTidy($keywordString), 50, 5) . MISC::br() . 
				$this->messages->text("hint", "keywords"));
// Existing keywords
			$pString .= TABLE::td(FORM::textareaInput(MISC::b($this->messages->text("resources", "availableKeywords")), 
				"null", $this->html->dbToFormTidy(join(', ', $keywords)), 80, 25) . MISC::br() . 
				$this->messages->text("hint", "availableKeywords"));
			$pString .= TABLE::trEnd();
			$pString .= TABLE::tableEnd();
			$pString .= TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart();
			$pString .= MISC::br();
		}
		$pString .= FORM::hidden("id", $this->vars['id']);
		$pString .= MISC::p(FORM::formSubmit("Edit"), FALSE, 'right');
		$this->template->setVar('body', $pString);
		$this->template->setVar('formEnd', FORM::formEnd());
		return $this->template->process();
	}
// write to the database
	function edit()
	{
		if($this->session->getVar('resourceLock'))
			$this->badInput($this->errors->text("done", "note"));
		$this->checkInput2();
		$this->writeCategoryTable();
		$this->writeKeywordTable();
// update resource timestamp
		$this->db->update('WKX_resource_timestamp', array('timestamp' => $this->db->formatTimestamp()), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($this->vars['id']));
// lock reload
		$this->session->setVar('resourceLock', TRUE);
// email notification
		include_once("core/notify/NOTIFY.php");
		$notify = new NOTIFY($this->db);
		$notify->email($this->vars['id']);
// send back to view this resource with success message
		include_once("core/resource/RESOURCEVIEW.php");
		$resource = new RESOURCEVIEW($this->db, $this->vars);
		new CLOSE($this->db, $resource->view($this->success->text("categoryKeyword", " " . 
			$this->messages->text("misc", 'edited') . " "), 'lastSolo'));
	}
// write to WKX_resource_category
	function writeCategoryTable()
	{
		$fields[] = "categories";
// force to 'General' group if no group selected.
		if(!array_key_exists('groupIds', $this->vars))
			$values[] = 1;
		else
			$values[] = join(',', $this->vars['groupIds']);
		$recordset = $this->db->select(array('WKX_resource_category'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->vars['id']);
		if($this->db->numRows($recordset))
		{
			foreach($fields as $field)
				$updateArray[$field] = array_shift($values);
			$this->db->update('WKX_resource_category', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->vars['id']);
		}
		else
		{
			$fields[] = "id";
			$values[] = $this->vars['id'];
			$this->db->insert('WKX_resource_category', $fields, $values);
		}
	}
// write to WKX_resource_keyword
	function writeKeywordTable()
	{
		$keywordIds = $this->keyword->writeKeywordTable($this->vars);
		$checkKeywords = FALSE;
// Current keywords for this resource
		$recordset = $this->db->select(array('WKX_resource_keyword'), array('keywords'), 
			" WHERE " . $this->db->formatfield('id') . "=" . 
			$this->db->tidyInput($this->vars['id']));
		$oldRow = $this->db->fetchRow($recordset);
		if(!$keywordIds || empty($keywordIds))
		{
			$checkKeywords = $oldRow['keywords'];
			$this->db->delete('WKX_resource_keyword', 
				" WHERE " . $this->db->formatField('id') . "=" . $this->vars['id']);
			$this->db->optimize('WKX_resource_keyword');
			$this->keyword->removeHanging2($checkKeywords);
			return;
		}
		else if(!empty($oldRow))
			$checkKeywords = array_diff(explode(",", $oldRow['keywords']), $keywordIds);
		$fields[] = "keywords";
		$values[] = implode(',', $keywordIds);
		$recordset = $this->db->select(array('WKX_resource_keyword'), array('id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->vars['id']);
		if($this->db->numRows($recordset))
		{
			$updateArray['keywords'] = array_shift($values);
			$this->db->update('WKX_resource_keyword', $updateArray, 
				" WHERE " . $this->db->formatField('id') . "=" . $this->vars['id']);
		}
		else
		{
			$fields[] = "id";
			$values[] = $this->vars['id'];
			$this->db->insert('WKX_resource_keyword', $fields, $values);
		}
// remove keyword(s) if they no longer have resource attached to them
		if($checkKeywords)
			$this->keyword->removeHanging2(join(",", $checkKeywords));
	}
// Check we have appropriate input.  In addition to 'id' must be at least 'groupIds'
	function checkInput()
	{
		if(!array_key_exists('id', $this->vars) || !$this->vars['id'])
			$this->badInput($this->errors->text("inputError", "missing"));
		if(!array_key_exists('groupIds', $this->vars) || !$this->vars['groupIds'])
			$this->badInput($this->errors->text("inputError", "missing"));
	}
// Check we have appropriate input.
	function checkInput2()
	{
		if(!array_key_exists('id', $this->vars) || !$this->vars['id'])
			$this->badInput($this->errors->text("inputError", "missing"));
	}
// Error handling - send them back to view a resource.
	function badInput($error)
	{
		include_once("core/resource/RESOURCEVIEW.php");
		$resource = new RESOURCEVIEW($this->db, $this->vars);
		new CLOSE($this->db, $resource->view($error, 'lastSolo'));
	}
}
?>
